<?php
/**
 * @file name : servicespost.php
 * @package   : thokim
 * @author    : Vo Thanh Minh
 * @email     : <thanhminhld@yahoo.com - thanhminhld@gmail.com>
 * @copyright : 2011
 *
 */
if (!defined('BASEPATH')) {
    exit('No direct script access');
}

class Servicespost extends Base_Controller
{
    /**
     * __construct
     * @access public
     * @param
     * @return
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
      * _remap
      * @access public
      * @param
      * @return
      */
    public function _remap( $method )
    {
        switch ($method) {

            case 'add':
            case 'edit':
                $this->addEditServicespost();
                break;

            case 'save':
                $this->saveServicespost();
                break;

            case 'del':
                $this->delServicespost();
                break;

            default:
                $this->index();
        }
    }
    /**
     * @function index
     * @access     private
     * @param
     * @return
     */
    private function index()
    {
        $controlName    = $this->input->get_post('c');
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Config for paging
         */
        $arrWhere = array('lang_id' => $this->lang_default);
        $this->load->library('pagination');
        $config['base_url'] = 'http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER["SCRIPT_NAME"])
                            . '/?c=' . $controlName;
        $totalRows = $this->servicespost_model->getTotalRows($arrWhere);
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 10;
        $config['num_links'] = 2;
        $config['page_query_string'] = TRUE;

        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['cur_tag_open'] = '&nbsp;<font color=#FF0000><strong>';
        $config['cur_tag_close'] = '</strong></font>';

        $this->pagination->initialize($config);
        $str_paging = $this->pagination->create_links();
        $this->msmarty->assign('paging',$str_paging);

        $offset = isset($_GET['per_page']) ? $_GET['per_page'] : 0;
        /**
         * End paging
         */
        $modulesList = $this->servicespost_model->loadList($arrWhere, $config['per_page'], $offset);

        $data = array('urlControlName'  => '?c=' . $controlName,
                      'modulesList'        => $modulesList,
                      'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp);

        $this->msmarty->view($controlName . '/admin.servicespost_manage', $data);
    }
    /**
     * @function addEditServicespost
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
    private function addEditServicespost()
    {
        $controlName = $this->input->get_post('c');
        $langObj     = $this->lang_model->getLang();
        $service_id  = $this->input->get_post('service_id');
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Load record for edit case
         */
        $records = array();
        if (is_numeric($service_id) && $service_id > 0) {
            $records = $this->servicespost_model->loadRecord($service_id);
        }
        $category_id  = -1;
        $service_show = 'Y';
        $service_img = '';
        $service_focus = '';
        $service_command = '';
        foreach ($langObj as $k => $vlang) {
            $arrLang[$k]['id'] = $vlang->id;
            $arrLang[$k]['name'] = $vlang->name;
            $arrLang[$k]['default'] = $vlang->default;
            foreach($records as $recd) {
                if ($recd->lang_id == $vlang->id) {
                    $arrLang[$k]['serviceObj'] = $recd;
                    $category_id   = $recd->category_id;
                    $service_show     = $recd->service_show;
                    $service_img      = $recd->service_img;
                    $service_focus    = $recd->service_focus;
                    $service_command  = $recd->service_command;
                    break;
                }
            }
        }
        /**
         * Get category list
         */
        $offset = 0;
        $categoryList = $this->servicescategory_model->loadList(array('lang_id' => $this->lang_default),
                                                                'all', $offset , 'category_id' , 'ASC');
        $categoryDropList = $this->servicescategory_model->recursiveLoadCategory(0, $categoryList, $category_id);
        /**
         * Your code addedit here
         */
        $data = array('actionForm'      => '?c=' . $controlName . '&m=save',
                      'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp,
                      'service_id'      => $service_id,
                      'category_id'     => $category_id,
                      'categoryList'    => $categoryDropList,
                      'service_show'    => $service_show,
                      'service_focus'   => $service_focus,
                      'service_img'     => $service_img,
                      'service_command' => $service_command,
                      'imgAppPath'      => UPLOAD_PATH . $controlName . '/');
        $this->msmarty->assign('langList', $arrLang);
        $this->msmarty->view($controlName . '/admin.servicespost_addedit', $data);
    }
    /**
     * @function saveServicespost
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
    private function saveServicespost()
    {
        $controlName    = $this->input->get_post('c');
        if ($_SERVER['REQUEST_METHOD']==='POST') {

            $data['category_id'] = $this->input->post('category_id');
            $data['service_title'] = $this->input->post('service_title');
            $data['service_title_url'] = convert2Alias($this->input->post('service_title'));
            $data['service_desc'] = $this->input->post('service_desc');
            $data['service_detail'] = $this->input->post('service_detail');
            $data['service_show'] = $this->input->post('service_show');
            $data['service_focus'] = $this->input->post('service_focus');
            $data['service_command'] = $this->input->post('service_command');
			$service_id              = $this->input->post('service_id');

			if ($service_id > 0) {
				$fUpdate       = true;
				$data['service_id']  = $service_id;
			} else {
				$fUpdate       = false;
			}
			/**
			 * Load lang to show msg
			 */
			$this->lang->load('success', $this->lang_tag);
			$this->lang->load('error', $this->lang_tag);
            /**
             * Check error input
             */
            if ( ! is_numeric($data['category_id']) || $data['category_id'] <= 0) {
                $this->messages->add($this->lang->line(), 'error');
                defaultPage($controlName);
            }
            if (isset($_FILES['service_img']['name']) &&
                preg_match('/\.jpg|\.JPG/', $_FILES['service_img']['name'])) {
                $response = $this->do_upload('service_img', true, array('width' => '150',
                                                                        'height' => '105'));
                if ($response['status'] == 'Error') {
                    defaultPage($controlName);
                }
				$data['service_img'] = $response['file_name'];
                $data['service_img_resize'] = $response['resize_name'];
                // Delete old file
                if (is_numeric($service_id) && $service_id > 0) {
                    $arrNews = $this->servicespost_model->loadRecord($service_id);
                    $oldImg = '';
                    $oldImgResz = '';
                    foreach($arrNews as $newsObj) {
                        $oldImg = $newsObj->service_img;
                        $oldImgResz = $newsObj->service_img_resize;
                        break;
                    }
                    if (file_exists(UPLOAD_PATH . $controlName . '/' . $oldImg)) {
                        unlink(UPLOAD_PATH . $controlName . '/' . $oldImg);
                    }
                    if (file_exists(UPLOAD_PATH . $controlName . '/' . $oldImgResz)) {
                        unlink(UPLOAD_PATH . $controlName . '/' . $oldImgResz);
                    }
                }
            }
			///// Start transaction /////
			/////////////////////////////
			$this->db->trans_begin();

			$ret = $this->servicespost_model->store($data, 'service_id', true, $fUpdate);

			if ($ret == FALSE) {
			    $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
			    // Rollback transaction
			    $this->db->trans_rollback();
			} else {

                if ($fUpdate) {
                    $this->messages->add($this->lang->line('db_update_success'), 'success');
                } else {
                    $this->messages->add($this->lang->line('db_insert_success'), 'success');
                }
                // Commit transaction
                $this->db->trans_commit();
			}

        }
        defaultPage($controlName);
    }
    /**
     * @function delServicespost
     *
     * @author      Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access     private
     * @param
     * @return     void
     */
    private function delServicespost()
    {
        $controlName    = $this->input->get_post('c');
        $news_id = $this->input->get_post('service_id');
		$imgPath = UPLOAD_PATH . $controlName . '/';
        /**
         * Load lang to show msg
         */
		$this->lang->load('success', $this->lang_tag);
		$this->lang->load('error', $this->lang_tag);
        if ( ! is_numeric($news_id) || $news_id <= 0) {
            $this->messages->add($this->lang->line('value_stranfer_err'), 'error');
            defaultPage($controlName);
        }
        $arrNews = $this->servicespost_model->loadRecord($news_id);
        foreach($arrNews as $newsObj) {
            $oldImg = $newsObj->service_img;
            if (file_exists($imgPath . $oldImg)) {
                unlink($imgPath . $oldImg);
            }
        }
        $this->db->trans_begin();
        $ret = $this->servicespost_model->deleteTbl(array('service_id' => $news_id), 'service_id');
        if ($ret == FALSE) {
            $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
            // Rollback transaction
            $this->db->trans_rollback();
        } else {
            $this->messages->add($this->lang->line('db_delete_success'), 'success');
            $this->db->trans_commit();
        }
		defaultPage($controlName);
    }
    /**
     * @function getErrMsg
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $msgBoxDisp, $clsType, $clsIcon
     * @return   array
     */
    private function getErrMsg(&$msgBoxDisp, &$clsType, &$clsIcon)
    {
        $messages = $this->messages->get();

        if (!is_array($messages)) {
            $messages = array();
            $msgBoxDisp = 'none;';
        } else {
            foreach($messages as $type => $message) {
                if(!empty($message)) {
                    if ($type == 'error') {
                        $clsType = $type;
                        $clsIcon = 'errorIcon';
                    } else if ($type == 'success') {
                        $clsType = $type;
                        $clsIcon = 'successIcon';
                    }
                    break;
                }
            }
        }
        $this->messages->clear();
        return $messages;
    }
    /**
     * @function do_upload
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $imgFieldName
     * @return   Array
(
    [status] => Success
    [error] =>
    [file_name] => Bilitis_-_Guitar.mp3
    [file_type] => audio/mpeg
    [file_path] => /opt/lampp/htdocs/chuanghiemquang/application/uploads/songmusic/
    [full_path] => /opt/lampp/htdocs/chuanghiemquang/application/uploads/songmusic/Bilitis_-_Guitar.mp3
    [raw_name] => Bilitis_-_Guitar
    [orig_name] => Bilitis_-_Guitar.mp3
    [file_ext] => .mp3
    [file_size] => 1969.05
    [is_image] =>
    [image_width] =>
    [image_height] =>
    [image_type] =>
    [image_size_str] => Bilitis_-_Guitar_thumb.mp3
)
     */
    private function do_upload($imgFieldName = '', $resizeImg = FALSE, $resizeWH = array())
    {
        $response = array('status' => '',
                          'error'  => '');
        if ( ! is_string($imgFieldName) || strlen($imgFieldName) <= 0) {
            return $response = array('status' => 'Error',
                                     'error'  => '');
        }
        $controlName = $this->input->get_post('c');
        if (is_string($controlName) && strlen($controlName) > 0 &&
            function_exists('realpath') && @realpath(UPLOAD_PATH . $controlName) == FALSE) {
            mkdir(UPLOAD_PATH . $controlName, 0777);
        }
        if ($_SERVER['REQUEST_METHOD']==='POST') {
            $config['upload_path']   = UPLOAD_PATH . $controlName;
            $config['allowed_types'] = 'jpg|jpeg';
            $config['encrypt_name']  = FALSE;
            $this->load->library('upload', $config);

            if( !$this->upload->do_upload($imgFieldName) ) {
                $response['status'] = 'Error';
                $response['error'] = $this->upload->display_errors();

            } else {
                $response['status'] = 'Success';
                $data = $this->upload->data();
                $response = array_merge($response, $data);
                if ($resizeImg == TRUE && is_array($resizeWH) &&
                    $resizeWH['width'] > 0 && $resizeWH['height'] > 0) {
                    $file_name = $response['file_name'];
                    $file_name = substr($file_name, strrpos($file_name, " "));
                    /* This config for resize image */
                    $configReZ['image_library'] = 'gd2';
                    $configReZ['create_thumb']  = TRUE;
                    $configReZ['width']         = $resizeWH['width'];
                    $configReZ['height']        = $resizeWH['height'];
                    $configReZ['master_dim']    = 'auto';
                    $configReZ['source_image']  = UPLOAD_PATH . $controlName . '/' . $file_name;
                    $this->load->library('image_lib', $configReZ);

                    $response['resize_status']  = '';
                    $response['resize_err']     = '';
                    $response['resize_name']    = '';
                    if (! $this->image_lib->resize()) {
                        $response['resize_status']    = 'Error';
                        $response['resize_err'] = $this->image_lib->display_errors() . $configReZ['source_image'];
                    } else {
                        $response['resize_status']    = 'Success';
                        $ext = substr($file_name, strrpos($file_name, "."));
                        $file_name = substr($file_name, 0, strrpos($file_name, '.'));
                        $response['resize_name'] = $file_name . '_thumb' . $ext;
                    }
                }
            }
        }
        return $response;
    }
}
